import React, { useEffect, useRef, useState } from "react";
import { Essaycontentwrap } from "./style";
import MdEditor from "md-editor-rt";
import Comment from "../comment";

import { formattime, getElementTop } from "@/utils";
import { useNavigate, useParams } from "react-router-dom";
import { addviews, changcollect, getessaydetail } from "@/apis/essay";
import classNames from "classnames";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { rootState } from "@/store";
import { usertype } from "@/store/reducers/home";
import { message } from "antd";
import Routertran from "@/components/routertran";
import { getcollectidarraction, loginpatch } from "@/store/action/home";

interface propinter {
  author: {
    avatar: string;
    id: number;
    username: string;
  };
  content: string;
  cover: string;
  createAt: string;
  id: number;
  label_id: number;
  labelname: string;
  title: string;
  views: number;
  label: string;
  collectcount: number;
}
export default function EssayContent() {
  const params = useParams();
  const navigate = useNavigate();
  const dispatch = useDispatch<any>();
  //文章
  const [essay, setEssay] = useState<propinter>();
  //记录所有标题到文档顶端的距离
  const [totop, settoTop] = useState<number[]>([]);
  //记录目录
  const [catalist, setCatalist] =
    useState<{ name: string; content: string }[]>();
  //记录当前应该显示第几个标题
  const [index, setIndex] = useState<number>(0);
  const catalistref = useRef<HTMLUListElement>(null);

  const { collectarr, user, essaypretheme } = useSelector(
    (store: rootState) => ({
      collectarr: store.home.thumbdobj.collectarr,
      user: store.home.user,
      essaypretheme: store.home.essaypretheme,
    }),
    shallowEqual
  );
  //增加浏览量
  useEffect(() => {
    if (!params.id) return;
    addviews(parseInt(params.id as string))
      .then(() => getessaydetail(params.id as string))
      .then((res: any) => {
        setEssay(res.result);
      });
  }, [params]);
  //处理导航
  useEffect(() => {
    if (essay?.id) {
      //这里必须要延时，否则会出现dom未加载完成就开始计算getBoundingClientRect
      setTimeout(() => {
        const mdeditor = document.querySelector(".mdeditor");
        let c = mdeditor?.childNodes[0].childNodes[0].childNodes[0].childNodes;
        let newc: any = [].slice.call(c);
        newc = newc.filter((item: any) =>
          ["h1", "h2", "h3", "h4", "h5"].includes(item.localName)
        );
        const totoparr: number[] = [];
        const catalistarr: { name: string; content: string }[] = [];
        newc.forEach((item: any) => {
          //下面两种方式相同（有bug）
          // totoparr.push(item.getBoundingClientRect().top);
          totoparr.push(getElementTop(item, document.documentElement));

          catalistarr.push({ name: item.localName, content: item.innerText });
          settoTop(totoparr);
          setCatalist(catalistarr);
        });
      }, 1000);
    }
  }, [essay]);
  useEffect(() => {
    if (totop.length > 0) {
      window.addEventListener("scroll", () => {
        for (let i = 0; i < totop.length - 1; i++) {
          if (document.documentElement.scrollTop > totop[i] - 300) {
            setIndex(i);
            catalistref.current?.scrollTo(0, (i - 5) * 40);
          }
        }
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [totop]);
  //页面滚动到指定标题
  const totitle = (ind: number) => {
    window.scrollTo(0, totop[ind] - 200);
    setIndex(ind);
  };
  //收藏或者取消收藏
  const addcollect = async () => {
    if (!(user as usertype).id) return message.warning("请登录");
    try {
      //取消收藏
      await changcollect((user as usertype).id, essay?.id as number);
      getessaydetail(params.id as string).then((res: any) => {
        setEssay(res.result);
      });
      dispatch(getcollectidarraction((user as usertype).id));
    } catch (e) {
      dispatch(loginpatch({}));
      message.error("身份失效");
    }
  };
  return (
    <Essaycontentwrap>
      {essay ? (
        <div className="editor">
          <img src={essay.cover} alt="" />
          <div className="topcontent">
            <div className="title">{essay.title}</div>
            <div className="main">
              <div className="left">
                <img
                  onClick={(e) => navigate(`/userpage/${essay.author.id}`)}
                  src={essay.author.avatar}
                  alt=""
                />
                <div className="right">
                  <div className="name">{essay.author.username}</div>
                  <div className="time">{formattime(essay.createAt)}</div>
                </div>
              </div>
              <div className="right">
                <div className="left">
                  <span className="iconfont icon-liulanliang"></span>
                  <span>{essay.views}</span>
                </div>
                <div className="right">
                  <span
                    className={classNames({
                      "iconfont icon-jushoucanggift": true,
                      shoucangactive: collectarr.includes(essay.id),
                    })}
                    onClick={addcollect}
                  ></span>
                  <span>{essay.collectcount}</span>
                </div>
              </div>
            </div>
          </div>
          <MdEditor
            className="mdeditor"
            previewOnly
            modelValue={essay.content}
            theme={essaypretheme}
          ></MdEditor>
          <span className="label">
            <span className="iconfont icon-biaoqian_o"></span> {essay.label}
          </span>
          <Comment></Comment>
        </div>
      ) : (
        <Routertran width={500} height={350} left={300} top={300}></Routertran>
      )}
      <div className="catawrap">
        <div className="catalogtitle">导航</div>
        <hr></hr>
        {catalist ? (
          <ul className="catalog" ref={catalistref}>
            {catalist.map((item, i) => {
              return (
                <li
                  onClick={(e) => totitle(i)}
                  key={i}
                  className={index === i ? item.name + " active" : item.name}
                >
                  {item.content}
                </li>
              );
            })}
          </ul>
        ) : (
          <Routertran width={200} height={150} top={50} left={50}></Routertran>
        )}
      </div>
    </Essaycontentwrap>
  );
}
